/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.depsea.butterfly.common.db;

import org.depsea.butterfly.common.annotation.Beta;
import org.depsea.butterfly.common.exception.OperationNotSupportedException;

import java.time.LocalDateTime;

/**
 * Model 工具类
 *
 * @author jaune
 * @since 1.0.0
 */
public class ModelUtils {

    @Beta
    public static final boolean TRY_SET_BY_FIELD_NAME = true;

    private ModelUtils() {
    }

    public static void setCreateInfo(CreateInfo createInfo, Long userId) {
        createInfo.setCreateUser(userId);
        createInfo.setCreateTime(LocalDateTime.now());
    }

    public static void setUpdateInfo(UpdateInfo updateInfo, Long userId) {
        updateInfo.setUpdateUser(userId);
        updateInfo.setUpdateTime(LocalDateTime.now());
    }

    public static void setCreateUpdateInfo(CreateUpdateInfo createUpdateInfo, Long userId) {
        setCreateInfo(createUpdateInfo, userId);
        setUpdateInfo(createUpdateInfo, userId);
    }

    public static void trySetCreateInfo(Object entity, Long userId) {
        if (entity instanceof CreateInfo) {
            setCreateInfo((CreateInfo) entity, userId);
        } else if (TRY_SET_BY_FIELD_NAME) {
            trySetCreateInfoByFieldName(entity, userId);
        }
    }

    public static void trySetUpdateInfo(Object entity, Long userId) {
        if (entity instanceof UpdateInfo) {
            setUpdateInfo((UpdateInfo) entity, userId);
        } else if (TRY_SET_BY_FIELD_NAME) {
            trySetUpdateInfoByFieldName(entity, userId);
        }
    }

    public static void trySetCreateUpdateInfo(Object entity, Long userId) {
        trySetCreateInfo(entity, userId);
        trySetUpdateInfo(entity, userId);
    }

    @Beta
    private static void trySetCreateInfoByFieldName(Object entity, Long userId) {
        throw new OperationNotSupportedException();
    }

    @Beta
    private static void trySetUpdateInfoByFieldName(Object entity, Long userId) {
        throw new OperationNotSupportedException();
    }
}
